﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Top.Web;
using Top.Web.Api;
using Top.Web.Api.Filters;
using Top.Core;
using Top.PointStore.Business;
using Top.PointStore.Business.Models;
using Top.PointStore.Web.Filters;
using System.Diagnostics;
//using Top.PointStore.Filters;

namespace Top.PointStore.Controllers
{
    /// <summary>
    /// 商品展示
    /// </summary>        
    public class ProductShowController : ApiBase
    {
        /// <summary>获取上架产品列表
        /// </summary>
        /// <param name="categoryKid">商品分类</param>
        /// <param name="stock">是否已售完:0、未售完，1、已售完</param>
        /// <param name="keyWords">关键词</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
        [Login]
        [Provider]
        public object GetSoldoutProductList(int cityKid, int categoryKid, string stock, string keyWords, int pageIndex = 1, int pageSize = 20)
        {
            return ProductShowManager.GetSoldoutProductList(cityKid, pUser.PointStoreAuth.F_CityKid, categoryKid, stock, keyWords, Pager.Create(pageIndex, pageSize));
        }


        public static bool statusLock = false;
        //<summary>产品上架与下架 ：0、下架，1、上架
        //</summary>
        //<returns></returns>
        [Login]
        [NoIdempotent]
        public object Status(int productKid)
        {
            int newID = 0;
            if (!statusLock)
            {
                statusLock = true;
                int status = Get("status", 0);
                newID = ProductShowManager.ProductSoldoutAdded(productKid).Result;
                if (status == 0)
                {
                    SystemManager.AddLog(User.CrmUserID, "ProductSoldout", "操作人" + User.Name + "下架商品编号(" + productKid + ")一条记录").Wait(); ;
                }
                else
                {
                   SystemManager.AddLog(User.CrmUserID, "ProductAdded", "操作人" + User.Name + "上架商品编号(" + productKid + ")一条记录").Wait();
                }
                statusLock = false;
            }
            else
            {
                throw new WebApiException("操作太频繁,请稍后再试");
            }            
            return newID;

        }


        /// <summary>
        /// 获取产品列表
        /// </summary>
        /// <param name="categoryKid">商品分类</param>
        /// <param name="status">展示状态:0、下架，1、上架，2、失效</param>
        /// <param name="keyWords">产品名称</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页数量</param>
        [Login]
        public object GetList(int cityKid, int categoryKid, string status, string keyWords, int pageIndex = 1, int pageSize = 20)
        {
            return ProductShowManager.GetList(cityKid, categoryKid, status, keyWords,pUser.PointStoreAuth.F_CityKid, Pager.Create(pageIndex, pageSize));
        }


        /// <summary>添加或修改展示信息
        /// </summary>
        /// <returns></returns>
        [Login]
        [Provider]
        public async Task<object> Save(int productKid, int ruleKid, string showName, DateTime? addedTime, DateTime? soldoutTime, int kid, int sort, int status)
        {
            if (ruleKid <= 0)
            {
                throw new WebApiException(ExceptionCode.ParameterError, "规则编号不能为空！");
            }

            if (string.IsNullOrEmpty(showName))
            {
                throw new WebApiException(ExceptionCode.ParameterError, "展示名称不能为空！");
            }

            var model = new T_ProductShow();
            model.Kid = kid;
            model.F_ProductKid = productKid;
            model.F_ExchangeRuleKid = ruleKid;
            model.F_AddedTime = addedTime ?? DateTime.Now;
            model.F_SoldoutTime = soldoutTime ?? DateTime.Now.AddDays(30);
            model.F_ShowName = showName;
            model.F_Sort = sort;
            model.F_Status = status;
            var result = 0;
            if (model.Kid > 0)
            {
                result = await ProductShowManager.Update(model);
            }
            else
            {
                result = await ProductShowManager.Add(model);
            }
            switch (result)
            {
                case 0:
                    throw new WebApiException("操作失败");
                case -1:
                    throw new WebApiException("商品id有误");
                case -2:
                    throw new WebApiException("兑换规则id有误");
                default:
                    break;
            }
            return result;
        }


        /// <summary>根据编号得到一条记录
        /// </summary>
        [Login]
        public async Task<object> Get(int productKid)
        {
            return await ProductShowManager.GetModel(productKid, User);
        }

        /// <summary> 购买商品
        /// </summary>
        /// <param name="productKid"></param>
        /// <returns></returns>
        [Login]
        public async Task<int> Buy(int productKid)
        {
            var res = await ProductShowManager.Buy(productKid, User);
            switch (res)
            {
                case 0:
                    throw new WebApiException("兑换失败");
                case -1:
                    throw new WebApiException("活动未开启");
                case -2:
                    throw new WebApiException("超出活动时间范围");
                case -3:
                    throw new WebApiException("经纪人不存在");
                case -4:
                    throw new WebApiException("经纪人积分不足");
                case -5:
                    throw new WebApiException("库存不足");
                case -6:
                    throw new WebApiException("超出用户兑换数量");
                case -7:
                    throw new WebApiException("该商品当日兑换数量已满");
                case -8:
                    throw new WebApiException("兑换时间有误");
                case -9:
                    throw new WebApiException("未到商品兑换开始时间");
                case -10:
                    throw new WebApiException("商品兑换时间已结束");
                default:
                    break;
            }
            return res;
        }

        ///// <summary>
        ///// 产品上架与下架
        ///// typeId ：0、下架，1、上架
        ///// </summary>
        ///// <returns></returns>
        // [Login]
        //public object Status(int productKid, int status)
        //{

        //    if (status == 0)
        //    {
        //        SystemManager.AddLog(User.CrmUserID, "ProductSoldout", "操作人" + User.Name + "下架商品编号(" + productKid + ")一条记录");
        //        return ProductShowManager.ProductSoldout(productKid);
        //    }
        //    else
        //    {
        //        SystemManager.AddLog(User.CrmUserID, "ProductAdded", "操作人" + User.Name + "上架商品编号(" + productKid + ")一条记录");
        //        return ProductShowManager.ProductAdded(productKid);

        //    }
        //}

        /// <summary>展示商品数据列表
        /// </summary>
        /// <returns></returns>
        [NoLogin]
        public object GetProductShow(int isMeskill, int pageIndex = 1, int pageSize = 12)//
        {
            try
            {
                int cityid = 0;
                bool isDistribute = false;
                if (User.IsBroker && User.BrokerID != 0)
                {
                    if (MemoryTable.TB_Broker.ContainsKey(User.BrokerID))
                    {
                        var broker = MemoryTable.TB_Broker[User.BrokerID];
                        if (broker != null)
                        {
                            cityid = broker.F_CityKid ?? 0;
                            isDistribute = broker.IsFenXiao == 1 ? true : false;
                        }
                    }
                    else
                    {
                        var broker = MemoryTable.GetBroker(User.BrokerID).Result;
                        if (broker != null)
                        {
                            cityid = broker.F_CityKid ?? 0;
                            isDistribute = broker.IsFenXiao == 1 ? true : false;
                        }
                    }
                }
                else if (User.IsCrmUser && User.CrmUserID != 0)
                {
                    if (MemoryTable.Map_CrmUserCity.ContainsKey(User.CrmUserID))
                    {
                        cityid = MemoryTable.Map_CrmUserCity[User.CrmUserID];
                    }
                    else
                    {
                        cityid = MemoryTable.GetCityKid(User.CrmUserID).Result.F_CityKid;
                    }

                }

                List<T_ProductShowExpandV3> list = ProductShowManager.GetProductShow_Memory(isMeskill, cityid, Pager.Create(pageIndex, pageSize)).Where(a => a != null).ToList();

                return list;
            }
            catch (Exception ex)
            {
                //Trace.Write(ex, "获取商品列表异常");
                throw new WebApiException("系统正忙，请稍后刷新");
            }
           
        }


        /// <summary>删除记录
        /// </summary>
        /// <param name="kids"></param>
        /// <returns></returns>
        [Login]
        public async Task<object> Delete(string kids)
        {
            await SystemManager.AddLog(User.CrmUserID, "ProductDelete", "操作人" + User.Name + "删除商品编号为(" + kids + ")的记录");
            if (kids.Split(',').Length >= 2)
            {
                return await ProductShowManager.DeleteList(kids);
            }
            else
            {
                return await ProductShowManager.Delete(int.Parse(kids));
            }

        }
    }
}
